<?php
if (! defined ( 'BASEPATH' ))
	exit ( 'No direct script access allowed' );

/**
 * 
 * @author xuelange
 *
 */
class Files extends MY_Controller {
	
	// 每页显示条数
	private $page = 100;
	private $curPage = 1;
	private $totalPage = 0;
	private $colName = "creation_ts";
	private $sortDesc = "desc";
	
	public function __construct() {
		parent::__construct ();
		//log_message ( 'debug', "Files  Class Initialized" );
		$this->load->service("user_info_service");
		$this->load->service("user_files_service");
	}
	
	public function index() {
		$this->head_user_info();
		$type = (int)$this->input->get ( "type" );
		if(!in_array($type,array(0,1,2)))
		{
			show_404();
		}
		$this->template->assign ( "s_id", "" );
		$this->template->assign ( "file_module_type", $type );
		if(!$type){
			//只在所在文件显示批量操作tool
			$this->template->assign ( "show_tool", true);
		}
		//$this->template->assign ( "file_list", $newList );
		$this->template->assign ( "totalPage", 0 );
		$this->template->assign ( "fileTotal", 0 );
		$this->template->assign ( "page", 0 );
		$this->template->view ( 'files.tpl');
	}

	/**
	 * 获取文件或文件夹具体内容
	 * @param string $ftype
	 * @param string $fid
	 * @return bool
	 */
	public function get_detail($ftype=0,$fid="")
	{
		if(empty($fid))
		{
			Common::ajax_return(1003);
			/*common::prf_json(FALSE,NULL);
			return;*/
		}
		$ret = array();

		$info = $this->user_files_service->get_detail($this->uid,$ftype,$fid);
		/*
		 *
				that.isFobbin = !josnData.data.isOpen;
		 * "name" : josnData.data.f_name,
					"size" : josnData.data.f_size,
					"life_span" : life_span,
					"f_pwd" : f_pwd,
					"auto_del" : auto_del,
					"only_one" : only_one,
					"f_dec" : josnData.data.f_dec,
					"f_id" : josnData.data.f_id,
					"f_type" : josnData.data.f_type,
					"f_count" : josnData.data.f_count
		var life_span = josnData.data.life_span;
				var auto_del = josnData.data.delete_after_expired;
				var only_one = josnData.data.open_counter;
				var f_pwd = josnData.data.f_pwd;

		*/
		if($info==FALSE)
		{
			Common::ajax_return($this->user_files_service);
		}
		if(!empty($info))
		{
			$ret['f_id'] = (int)$info['id'];
			$ret['f_name'] = $info['name'];
			$ret['f_ext_name'] = isset($info['ext_name'])?$info['ext_name']:"";
			$ret['f_dec'] = $info['description'];
			$ret['f_type'] = (int)$ftype;
			$ret['f_count'] = $ftype==1?$this->user_files_service->get_folder_file_count($this->uid,$fid):0;
			$ret['f_size'] = $ftype==0?(int)$info['size']:0;
			$ret['isOpen'] = (int)$info['access_denied']==0?1:0;

			$life_span 				= ""; 	//过期时间
			$delete_after_expired 	= 0;	//自动销毁
			$open_counter			= 0;	//访问控制
			$pwd					= "";	//查阅密码
			$remain_viewed 			= 0;	//剩余可查阅次数

			if (! empty($info['data'])) {
				$policy = $this->policy_to_arr($info['data']);

				#过期时间
				if (isset($policy['life_span']) && ($policy['life_span']['value_set'] !== 0))
					$life_span = date("Y-m-d H:i:s", $policy['life_span']['value_set']);

				if (isset($policy['delete_after_expired']))
					$delete_after_expired = (int)$policy['delete_after_expired']['value_set'];

				if (isset($policy['open_counter'])) {
					$open_counter  = (int)$policy['open_counter']['value_set'];
					$used_open_time = isset($policy['open_counter']['value']) ?
						(int)$policy['open_counter']['value'] : 0;
					$remain_viewed = $open_counter - $used_open_time;
					if ($remain_viewed < 0) $remain_viewed = 0;
				}

				if (isset($policy['read_pwd']))
					$pwd = $policy['read_pwd']['value_set'];
			}

			//策略处理
			$ret['life_span'] = $life_span;
			$ret['delete_after_expired'] = $delete_after_expired;
			$ret['open_counter'] = $open_counter;
			$ret['f_pwd'] = $pwd;
			$ret['remain_viewed'] = $remain_viewed;

		}
		else
		{
			if($ftype==1)
			{
				Common::ajax_return(7100);
			}
			else
			{
				Common::ajax_return(7001);
			}
		}
		Common::ajax_return(0,NULL,array("data"=>$ret),FALSE);
		return true;
	}
	
	private function get_ep_files($index)
	{
		$fileTotal =$this->files_model->getEpTotal($this->uid);
		$totalPage = ceil ( $fileTotal / $this->page );
		
		$filelist = $this->files_model->getEps($this->uid,$this->page,0);
		$newList = $this->format($filelist, $index);
		$this->template->assign ( "file_list", $newList );
		$this->template->assign ( "totalPage", $totalPage );
		$this->template->assign ( "fileTotal", $fileTotal );
		$this->template->assign ( "page", $this->page );
		$this->template->view ( 'files.tpl' );
		
		return;
	}
	
	private function get_ep_files_json($index)
	{
		$fileTotal =$this->files_model->getEpTotal($this->uid);
		$totalPage = ceil ( $fileTotal / $this->page );
			
		$filelist = $this->files_model->getEps($this->uid,$this->page,$index,$this->colName,$this->sortDesc);
		
		$newList = $this->format_to_json($filelist, $index);
			
		$paramArr = array(
				"totalPage" => $totalPage,
				"fileTotal" => $fileTotal,
				"page"		=> $this->page
		);
		common::prf_json ( TRUE, $newList, $paramArr );
		return;
	}
	
	private function get_dowloaded_file($type,$index)
	{
		$newList = array ();
		$totalPage = 0;
		$fileTotal = 0;
		
		// 获取某个用户所有文件列表
		$filelist =$this->files_model->get_files($this->uid,0,$this->page,0,$type,$this->colName,$this->sortDesc);
		if (!$filelist) {
			$this->template->assign ( "file_list", $newList );
			$this->template->assign ( "totalPage", $totalPage );
			$this->template->assign ( "fileTotal", $fileTotal );
			$this->template->assign ( "page", $this->page );
			$this->template->view ( 'files.tpl' );
			return;
		}
		
		$fileTotal = $this->files_model->getTotal($this->uid,0,array("downloaded" => "1"));
		
		$totalPage = ceil ( $fileTotal / $this->page );
		
		if ($totalPage == 1)
			$totalPage = 0;
		
		$newList = $this->format($filelist, 0);
		
		$this->template->assign ( "file_list", $newList );
		$this->template->assign ( "totalPage", $totalPage );
		$this->template->assign ( "fileTotal", $fileTotal );
		$this->template->assign ( "page", $this->page );
		$this->template->view ( 'files.tpl' );
	}
	
	private function get_dowloaded_file_json($type,$index)
	{
		if($this->colName != "name"){
			$filelist =$this->files_model->get_files($this->uid,0,$this->page,$index,$type,$this->colName,$this->sortDesc);
		}else{
			$filelist =$this->files_model->get_files_sort_name($this->uid,0,$this->page,$index,$type,$this->sortDesc);
		}
		
		if (! $filelist) {
			log_message ( 'debug', "Files get_all list is null,list page > totalPage" );
			common::prf_json ( false, NULL, null );
			return false;
		}
		
		$newList = array();
		
		$fileTotal = $this->files_model->getTotal($this->uid,0,array("downloaded" => "1"));
		
		$totalPage = ceil ( $fileTotal / $this->page );
		if ($totalPage == 1)
			$totalPage = 0;
		
		$newList = $this->format_to_json($filelist, $index);
		
		$paramArr = array(
				"totalPage" => $totalPage,
				"fileTotal" => $fileTotal,
				"page"		=> $this->page
		);
		common::prf_json ( TRUE, $newList, $paramArr );
		return true;
	}
	
	private function format_to_json($filelist,$index)
	{
		$newList = array();
		foreach ( $filelist as $key => $arr ) {
			$fileArr = array();
			$fileArr['uuid'] =  $arr ['uuid'];
			$fileArr ['size'] = Common::get_file_size ( $arr ['size'] );
			$fileArr ['created_ts'] = date ( 'Y-m-d H:i', $arr ['creation_ts']/1000 );
			$fileArr ['index'] = ($index + 1 + $key);
			$fileArr ['type'] = Common::get_file_type ( $arr ['name'] );
			$fileArr ['name'] = $arr ['name'] ;
			if($arr ['access_denied'] == 1){
				$fileArr ['access_denied'] = $arr ['access_denied'] ;
			}
			$fileArr ['rid'] =  $arr['rid'];
		
			$newList[$key] = (object) $fileArr;
		}
		
		return $newList;
	}


	private function format($filelist,$index,$type=0)
	{
		if(empty($filelist))return array();
		$newList = array();
		if($type==0)
		{
			foreach ( $filelist as $k => $file ) {
				$newList [$k] ['id'] = $file ['id'];
				$newList [$k] ['type'] = $file['ext_name'];
				$newList [$k] ['fullName'] = $file['name'];
				$newList [$k] ['name'] = $file['name'].".".$file['ext_name'];
				$newList [$k] ['size'] = $this->user_info_service->format_space( $file ['size'] );
				$newList [$k] ['created_ts'] = date ( 'Y-m-d H:i', $file ['creation_ts'] );
				$newList [$k] ['uuid'] = $file ['id'];
				$newList [$k] ['rid'] =  $file['id'];
				$newList [$k]['index'] = ($index + 1 + $k);
				$newList [$k]['access_denied'] = (int)$file['access_denied'];
			}

		}
		else
		{
			foreach ( $filelist as $k => $file ) {
				$newList [$k] = $file;
				$newList [$k]['index'] = ($index + 1 + $k);
				$newList [$k] ['created_ts'] = date ( 'Y-m-d H:i', $file ['creation_ts'] );
				$newList [$k] ['creation_ts'] = date ( 'Y-m-d H:i', $file ['creation_ts'] );
				$newList [$k] ['uuid'] = $file ['id'];
				$newList [$k]['access_denied'] = (int)$file['access_denied'];
			}
		}
		//krsort($newList);
		return $newList;
	}

	/**
	 * 进入某一个文件夹
	 * @param int $folder_id
	 * @return bool
	 */
	public function cd($folder_id=0)
	{
		$folder_id = (int)$folder_id;
		$type = $this->input->get("type",true);
		$keyword = $this->input->get("keyword",true);
		$pcolName = $this->input->get("colName",true);
		//按字段名排序
		$psortdesc = $this->input->get("sortDesc",true);
		$pcolName = $this->filterColName($pcolName);

		$folder_info = $folder_id>0 ? $this->user_files_service->get_path_info($this->uid,$folder_id) :null;
		if($folder_info===FALSE)
		{
			Common::ajax_return($this->user_files_service);
		}
		//已下载文件
		if($type==1)
		{
			$files = $this->user_files_service->get_downloaded_file_list($this->uid,false,$keyword,$pcolName,$psortdesc);
			$list['files'] = $files['rows'];
			$list['total'] = $files['total'];
			$list['folders'] = array();
		}
		//已过期文件
		else if($type==2)
		{
			$files = $this->user_files_service->get_exp_file_list($this->uid,false,$keyword,$pcolName,$psortdesc);
			$list['files'] = $files['rows'];
			$list['total'] = $files['total'];
			$list['folders'] = array();
		}
		else
		{
			$fid= $folder_id;
			if(!empty($keyword))
			{
				$fid = FALSE;
			}

			//对%_.进行处理
			$keyword = str_replace("%", "\\%", $keyword);
			$keyword = str_replace("_", "\\_", $keyword);
			$keyword = str_replace(".", "", $keyword);

			$list = $this->user_files_service->get_list($this->uid,$fid,$keyword,$pcolName,$psortdesc);
		}
		$list['files']  = $this->format($list['files'],0,0);
		$list['folders']  = $this->format($list['folders'],0,1);
		if($list['files']===FALSE || $list['folders']===FALSE)
		{
			Common::ajax_return($this->user_files_service);
		}
		$folders = !empty($list['folders'])?Common::array_column($list['folders'],"name"):array();
		$new_folder_num = $this->user_files_service->get_new_folder_num($folders);
		$list['new_folder_num'] = $new_folder_num;
		$list['folder'] = $folder_info;
		if(!empty($list['folder']))
		{
			$list['folder']['uuid']=$list['folder']['id'];
		}
		Common::ajax_return(0,NULL,array("data"=>$list),FALSE);
		//common::prf_json ( TRUE, $list);
		//common::prf_json (FALSE,null);
		return true;
	}

	/*public function test_cd()
	{
		$ret =$this->user_files_service->get_path_info($this->uid,24);
		echo json_encode($ret);
	}*/

	public function get_all() {
		return;
		$page = $this->input->get ( "page" );
		$type = (int)$this->input->get ( "type" );


		$pid = $this->input->get ( "puuid" );
		//按字段名排序
		$pcolName = $this->input->get("colName");
		//按字段名排序
		$psortdesc = $this->input->get("sortDesc");
		
		$this->curPage = ( int ) $page;

		/*$pid = 0;
		if($fdr_uuid){
			$folder = $this->folder_mdl->get_folder_by_uuid($fdr_uuid);
			if(!$folder){
				common::prf_json ( FALSE, NULL,NULL,time(),TRUE,"folder is null");
				return;
			}
				
			$pid = $folder['id'];
		}*/
		
		/*$record = $this->curPage;
		if ($record > 0) {
			$record = ($this->curPage) * $this->page - $this->page;
		}
		if ($record < 0) {
			$record = 0;
		}*/
		
		$this->colName = $this->filterColName($pcolName);
		$this->sortDesc = $this->filterSortDesc($psortdesc);
		
		/*if($type == 2){
			$this->get_ep_files_json($record);
			return;
		}else if($type == 1){
			$this->get_dowloaded_file_json($type, $record);
			return;
		}*/
		$list = $this->user_files_service->get_list($this->uid,$pid,"",$this->colName,$this->sortDesc);
		/*if($this->colName != "name"){
			$filelist =$this->files_model->get_files($this->uid,$pid,$this->page,$record,$type,$this->colName,$this->sortDesc);
		}else{
			$filelist =$this->files_model->get_files_sort_name($this->uid,$pid,$this->page,$record,$type,$this->sortDesc);
		}*/
		
		
		/*if ($list['total']==0) {
			common::prf_json ( TRUE, NULL, null,time(),TRUE,"filelist is null" );
			return false;
		}
		
		$newList = array();
		$fileTotal = $this->files_model->getTotal($this->uid,$pid);
		
		$totalPage = ceil ( $fileTotal / $this->page );
		if ($totalPage == 1)
			$totalPage = 0;
		
		//第一页计算文件的个数
		$realIndex = $record;
		

		$folderTotal = $this->folder_mdl->getTotal($this->uid,$pid);
		$realIndex += $folderTotal;

	
		$newList = $this->format_to_json($filelist, $realIndex);
		
		$paramArr = array(
				"totalPage" => $totalPage,
				"fileTotal" => $fileTotal,
				"page"		=> $this->page
		);*/
		common::prf_json ( TRUE, $list);
		return true;
	}
	
	public function del() {
		$file_uuid = $this->input->post ( "file_id",TRUE );
		$this->db->select("id");
		$file = $this->db->get_where ( 'file', array (
				'uuid' => $file_uuid 
		) )->row_array ();
		if (! $file) {
			log_message ( 'debug', "files del  select file fail" );
			common::prf_json ( TRUE, time (), null );
			return false;
		}
		$flag = $this->files_model->update_status($file ['id']);
		
		if(!$flag){
			common::prf_json ( false, NULL, null );
			return false;
		}
		common::prf_json ( TRUE, NULL, null );
		
		//记录文件轨迹
		$this->load->model('trace_model');
		$this->trace_model->insert(4, $file_uuid);
		return true;
	}
	
	/**
	 * 更新文件概述信息
	 */
	public function update_detail(){
		$this->load->library ( 'form_validation' );
		$this->form_validation->set_rules('id', 'Id', 'required');
		$this->form_validation->set_rules('dec', 'Dec', 'required|max_length[255]');
		$fid = $this->input->post ( "id",TRUE);
		$dec = $this->input->post ( "dec",TRUE );
		$type = $this->input->post ( "type",TRUE );
		$dec = trim($dec);
		$ret = $this->user_files_service->update_description($this->uid,$fid,$type,$dec);
		Common::ajax_return($ret?0:$this->user_files_service);
		//common::prf_json ( $ret, NULL, null );
		/*if (! $file_uuid) {
			common::prf_json ( false, NULL, null );
			return false;
		}
		$tableName = 'file';
		if($type){
			$tableName = 'folder';
		}
		$this->db->select("id");
		$file = $this->db->get_where ( $tableName, array (
				'uuid' => $file_uuid
		) )->row_array ();
		if (! $file) {
			log_message ( 'debug', "files update_detail  select file fail" );
			common::prf_json ( TRUE, time (), null );
			return false;
		}
		$flag = $this->files_model->update_detail($file ['id'],$file_dec,$tableName);
		if(!$flag){
			common::prf_json ( false, NULL, null );
			return false;
		}
		common::prf_json ( TRUE, NULL, null );
		return true;*/
		
	}



	/**
	 * 过滤字段名
	 * @param unknown $colName
	 */
	private function filterColName($pcolName){
		$colName = "creation_ts";
		if($pcolName == "filename"){
			$colName = "name";
		}else if($pcolName == "filesize"){
			$colName = "size";
		}else if($pcolName=="filecreate")
		{
			$colName = "creation_ts";
		}
		return $colName;
	}
	
	/**
	 * 过滤排序升序降序
	 * @param unknown $colName
	 */
	private function filterSortDesc($psortDesc){
		$sortDesc = "desc";
		if($psortDesc == "asc"){
			$sortDesc = "asc";
		}
		return $sortDesc;
	}
	
	/*public function getAllTotalByPid(){
		$pid = $this->input->get("pid",TRUE);
		$type = $this->input->get("type",TRUE);
		if(!isset($pid)){
			$pid = 0;
		}
		if($type == 1){
			$where = array('downloaded'=>1);
			$total = $this->files_model->getTotal($this->uid,$pid, $where);
		} else if($type == 2){
			$total = $this->files_model->getEpTotal($this->uid);
		} else {
			$total = $this->files_model->getTotal($this->uid,$pid);
			$total += $this->folder_mdl->getTotal($this->uid,$pid);
		}
		common::prf_json ( TRUE, array("total"=>$total), null);
		return true;
	}*/
	
	
	/**
	 * 立即试用视图
	 */
	public function tryout(){
		if(!isset($_COOKIE['__TRYOUT__'])){
			redirect('files');
		} else {
			$this->template->view('tryout.tpl');
		}
	}

	/**
	 * 获取新建文件夹可用序号
	 */
	public function get_new_folder_num()
	{
		$folder_id = (int)$this->input->get("file_id",TRUE);
		$folders = $this->user_files_service->get_folder_list($this->uid,$folder_id,"","name","asc","name");
		//var_dump($folders);exit;
		if(empty($folders))
		{
			$num = 0;
		}
		else
		{
			$num = $this->user_files_service->get_new_folder_num(Common::array_column($folders['rows'],"name"));
		}
		Common::ajax_return(0,NULL,array("data"=>array("defindMax"=>$num)),FALSE);
		//common::prf_json ( , array("defindMax" =>$num));
	}

	public function add_folder()
	{
		$name = trim($this->input->get("name",TRUE));
		$pid = (int)$this->input->get("uuid",TRUE);//父文件夹uuid
		if(($name!='0' && empty($name)) || $pid<0)
		{
			Common::ajax_return(1003);
			//show_404();
		}
		$add = $this->user_files_service->add_folder($this->uid,$name,$pid);
		if($add === false)
		{
			Common::ajax_return($this->user_files_service);
			//common::prf_json(FALSE,NULL,NULL,time(),TRUE,$this->user_files_service->get_error("msg"));
			//return;
		}
		else
		{
			Common::ajax_return(0,NULL,array("data"=>$add),FALSE);
			//common::prf_json(TRUE,$add);
		}
		return true;
	}

	/**
	 * 重命名
	 */
	public function folder_rename()
	{
		$id = $this->input->get("id",TRUE);
		$name = trim($this->input->get("name",TRUE));

		if(strlen($name) == 0){
			/*common::prf_json(FALSE,NULL,NULL,time(),TRUE,"param name is null");
			return;*/
			Common::ajax_return(1003);
		}

		if(mb_strlen($name) > 255){
			Common::ajax_return(1003);
			/*common::prf_json(FALSE,NULL,NULL,time(),TRUE,"param name length is too longer ");
			return;*/
		}

		if(empty($id)){
			Common::ajax_return(1003);
			/*common::prf_json(FALSE,NULL,NULL,time(),TRUE,"id param is null");
			return;*/
		}

		$edit = $this->user_files_service->update_folder_name($this->uid,$id,$name);
		Common::ajax_return($this->user_files_service);
		/*if($edit === false)
		{
			common::prf_json(FALSE,NULL,NULL,time(),TRUE,$this->user_files_service->get_error("msg"));
			return;
		}
		common::prf_json(TRUE,NULL);*/
	}

	/**
	 * 获取文件夹子目录
	 * @get node 节点的id
	 */
	public function get_child()
	{
		$pid = (int)$this->input->get("node");
		$folders=$this->user_files_service->get_folder_list($this->uid,$pid,"","name","asc","id,name,has_children");
		$newList=array();
		if($folders)
		{
			foreach ($folders['rows'] as $key => $folder){
				$newList[$key]['label'] = $folder['name'];
				$newList[$key]['id'] = (int)$folder['id'];
				$newList[$key]['load_on_demand'] = ($folder['has_children'] >0) ? true : false;
			}
		}
		asort($newList);
		if ($pid == 0 || empty($folders)) {
			$arr = array();
			$arr['id'] = 0;
			$arr['label'] = "所有文件";
			if(!empty($newList))
			{
				$arr['children'] = array_values($newList);
			}
			echo json_encode(array($arr));
			return;
		}
		else
		{
			echo json_encode(array_values($newList));
			return;
		}
		//var_dump($folders);
		/*$folders=$this->user_files_service->get_folder_list();
		foreach ($folders as $key => $folder){
			$newList[$key]['label'] = $folder['name'];
			$newList[$key]['id'] = $folder['uuid'];
			$newList[$key]['load_on_demand'] = ($folder['has_children'] == 1) ? true : false;
		}
		if($uuid == "0"){
			$arr = array();
			$arr['id'] = "0";
			$arr['label'] = "所有文件";
			$arr['children'] = $newList;

			echo json_encode(array($arr));
			return;
		}
		echo json_encode($newList);
		return;*/

	}

	/**
	 * 移动文件位置
	 * @get|post files 文件列表
	 */
	public function move()
	{
		$files = $this->input->get_post("files",TRUE);
		$files = explode(",",$files);

		if(empty($files)){
			//show_404();
			Common::ajax_return(1003);
		}
		$to = (int)$this->input->get_post("folder_id",TRUE);
		$this->user_files_service->move($this->uid,$files,array(),$to);
		Common::ajax_return($this->user_files_service);
		//common::prf_json($ret,NULL);
	}

	/**
	 * 批量删除文件或者文件夹
	 * @get|post files 文件列表
	 * @get|post folders 文件夹列表
	 */
	public function delete()
	{
		$files = $this->input->get_post("files",true);
		$folders = $this->input->get_post("folders",true);
		if(empty($files) && empty($folders))
		{
			Common::ajax_return(1003);
			//show_404();
		}
		if(!empty($files))
		{
			$files = explode(",",$files);
		}
		if(!empty($folders))
		{
			$folders = explode(",",$folders);
		}
		$this->user_files_service->delete($this->uid,$files,$folders);
		$data = $this->user_info_service->get_format_space($this->uid);
		Common::ajax_return(0,NULL,array("data"=>$data),FALSE);
		//common::prf_json(true,$data);
	}

	/**
	 * 即时收回状态修改
	 */
	public function update_access_denied()
	{
		$files = $this->input->get_post("files",true);
		$folders = $this->input->get_post("folders",true);
		$denied = (int)$this->input->get_post("denied",true);
		if(($denied!=0 && empty($denied)) || (empty($files) && empty($folders)))
		{
			Common::ajax_return(1003);
			//show_404();
		}

		if(!empty($files) && !is_array($files))
		{
			$files = explode(",",$files);
		}
		if(!empty($folders) && !is_array($folders))
		{
			$folders = explode(",",$folders);
		}
		$all=false;
		$edit = $this->user_files_service->update_access_denied($this->uid,$files,$folders,$denied,$all);
		Common::ajax_return($this->user_files_service);
		/*if($edit!==false)
		{
			common::prf_json(true,null);
		}
		else
		{
			common::prf_json(false,null,$this->user_files_service->get_error());
		}*/
	}

    /**
     * 将json格式的策略转换成数组 k=>v 形式
     * @param $data 策略json格式的数据
     * @return array
     */
    public function policy_to_arr($str) {
        $arr = json_decode($str, TRUE);
        $new_data = array();
        foreach ($arr as $key => $value) {
			$des = $value['des'];
			unset($value['des']);
            $new_data[$des] = $value;
        }
        return $new_data;
    }

	/**
	 * 获取打包进度
	 */
	public function get_packet_percent()
	{
		$sess_data = $this->session->userdata("PACKET_LIST");
		//$test = !is_array($sess_data) || empty($sess_data)?FALSE:TRUE;
		//本地调试服务器处理
		$id = $this->input->get("id",TRUE);
		if(ENVIRONMENT=="development")
		{
			if(!is_array($sess_data) || empty($sess_data))
			{
				$sess_data=array();
			}
			$data=array();
			$step = 20;
			//var_dump($sess_data);
			$dpercent = $step;
			if(empty($id))
			{
				Common::ajax_return(1003);
			}
			else if(!isset($sess_data[$id]) || !isset($sess_data[$id]['percent']))
			{
				Common::ajax_return(1003);
			}
			else if($sess_data[$id]['percent']>=100 || $sess_data[$id]['percent']+20>=100)
			{
				$dpercent = 100;
				/*$data = $this->user_files_service->get_all_file_info_by_guid($id,NULL,NULL,NULL,"id,guid,name,size,type,ext_name,creation_ts,modify_ts,folder_id,source_guid,access_denied",NULL,NULL);*/
				//var_dump($id);exit;
				$params = $sess_data[$id]['params'];
				$data = $this->user_files_service->add_file($params['uid'],$params['name'],$params['size'],$params['mime_type'],$params['md5'],$params['source_guid'],$params['folder_id'],$params['guid']);
				if($data===FALSE)
				{
					Common::ajax_return($this->user_files_service);
				}
				$add_sec = $this->user_files_service->add_secure_file($data['id'],$params['size'],1,Common::uniqid(),Common::uniqid(),Common::uniqid());
				if($add_sec===FALSE)
				{
					return Common::ajax_return($this->user_files_service);
				}
				$default_path = $this->config->item("default_upload_path")."file/";
				if(!is_dir($default_path))
				{
					@mkdir($default_path,0777,true);
				}
				$save_path = $default_path.$params['source_guid'].".tmp";

				if($data['source_guid']==$params['source_guid'])
				{
					copy($params['file_path'],$save_path);
				}
				if(file_exists($params['file_path']))
				{
					@unlink($params['file_path']);
				}
				unset($sess_data[$id]);
			}
			else
			{
				$sess_data[$id]['percent'] += $step;
				$dpercent = $sess_data[$id]['percent'];
			}

			$this->session->set_userdata("PACKET_LIST",$sess_data);

			Common::ajax_return(0,NULL,array("percent"=>$dpercent,"id"=>$id,"data"=>$data),FALSE);
		}
		//线上服务器处理
		else
		{

			$redis = new Redis();
			$con = $redis->connect($this->config->item("host","redis"), $this->config->item("port","redis"), $this->config->item("timeout","redis"));
			if(!$con)
			{
				Common::ajax_return(1019);
			}
			//$this->redis->setex("testtest",10,"hahahah");
			$redis_data =  $redis->get($id);
			$data=json_decode($redis_data,true);
			if(!$data)
			{
				Common::ajax_return(1019);
			}
			if(isset($data['error_code']) && $data['error_code']>0)
			{
				Common::ajax_return($data['error_code']);
			}
			Common::ajax_return(0,NULL,array("percent"=>$data['percent'],"id"=>$id,"data"=>$data['data']),FALSE);
		}

	}


	public function export_source_file()
	{
		$this->load->library('traces');  //轨迹类
		$id = $this->input->get("id",TRUE);
		if(empty($id)) {
			show_404();
		}
		$data =  $this->user_files_service->get_all_file_info($id,null,null,null,"name,source_guid,ext_name",null,null);
		if(empty($data))
		{
			Common::show_message(Common::get_error_message(7001),Common::get_error_message(7001),"error","/");
		}
		$name = $data['name'].".".$data['ext_name'];
		$guid = $data['source_guid'];

		if(ENVIRONMENT=="development")
		{
			$test_source = "./resources/file/".$guid.".tmp";
			if(file_exists($test_source))
			{
				Traces::trace_file($id,Traces::EVENT_DOWNLOAD_SOURCE_FILE,"","",$this->uid);
				header('Content-Type:image/gif'); //指定下载文件类型
				header('Content-Disposition: attachment; filename="'.$name.'"'); //指定下载文件的描述
				header('Content-Length:'.filesize($test_source)); //指定下载文件的大小
				//将文件内容读取出来并直接输出，以便下载
				readfile($test_source);
				exit;
			}
			else
			{
				Common::show_message(Common::get_error_message(7001),Common::get_error_message(7001),"error","/");
			}
		}
		else
		{
			$download_exp = $this->config->item("download_expire_time");
			$link_id = Common::download_link($guid, "download_source".$id);
			if($link_id==FALSE){
				Common::ajax_return(7001);
			}

			Traces::trace_file($id,Traces::EVENT_DOWNLOAD_SOURCE_FILE,"","",$this->uid);
			$data = json_encode(array("guid"=>$guid,"name"=>rawurlencode($name)));
			$redis = new Redis();
			$connect = $redis->connect($this->config->item("host","redis"),$this->config->item("port","redis"),$this->config->item("timeout","redis"));
			if(!$connect)
			{
				Common::show_message(Common::get_error_message(1019),Common::get_error_message(1019),"error","/");
			}
			else
			{
				$set = $redis->setex($link_id,$download_exp,$data);
				if(!$set)
				{
					Common::show_message(Common::get_error_message(1019),Common::get_error_message(1019),"error","/");
				}
			}
			//redirect("/d?id=".$link_id);
			$this->template->view("simple_export.tpl",array(
				"url"=>"/d?id=".$link_id
			));
		}
	}

}
